<?php
// +----------------------------------------------------------------------
// | 留言板模块
// +----------------------------------------------------------------------
// | @link ( http://www.yurnero.net )
// +----------------------------------------------------------------------
// | @copyright
// +----------------------------------------------------------------------
// | @licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | @author Haijun Wu <nicholasinlove@126.com>
// +----------------------------------------------------------------------
// | $Id: GuestbookAction.class.php 123 2011-05-18 09:46:17Z nicholasinlove1986@gmail.com $
// +----------------------------------------------------------------------


class GuestbookAction extends BaseAction {

	public function index(){
        	
		//查询过滤
		$map  =	 array();
		$map['comment_visible'] = 1;
		$map['comment_type'] = 2;
		
		$gb  =  M ('Comment');
		import("@.ORG.Page");
		C ( 'PAGE_ROLLPAGE',C('page_roll') );
		$count = $gb->where($map)->count();
		$p = new Page ($count, C('guestbook_num'));
		$list = $gb->where($map)->limit($p->firstRow.','.$p->listRows)->order('comment_id desc')->findAll();
		
		foreach ($list as $k=>$v) {
			$list[$k]['comment_email'] = get_gravatar($list[$k]['comment_email'], $s = 80, $d = C('avatar_default'), $r = C('avatar_rating'));
			$list[$k]['comment_addtime'] = date('F jS, Y', $list[$k]['comment_addtime']).' at '.date('G:i', $list[$k]['comment_addtime']);
			$list[$k]['comment_content'] = convert_smilies($list[$k]['comment_content']);
			if ($list[$k]['comment_recontent']) {
				$list[$k]['comment_retime'] = date('F jS, Y', $list[$k]['comment_retime']).' at '.date('G:i', $list[$k]['comment_retime']);
				$list[$k]['comment_recontent'] = convert_smilies($list[$k]['comment_recontent']);
			}
		}
		
		$p->setConfig('theme',C('index_page_theme'));
		$page = $p->show ();
		
		$this->assign('comment_author', Cookie::get('comment_author_'.C('COOKIEHASH')));
		$this->assign('comment_email', Cookie::get('comment_email_'.C('COOKIEHASH')));
		$this->assign('comment_url', Cookie::get('comment_url_'.C('COOKIEHASH')));
		$this->assign('page', $page);
		$this->assign('list', $list);
		$this->display();
    }
	
	public function post() {
	
	    //验证码
	    if (C('verify')) {
			if($_SESSION['verify'] != md5($_POST['verify'])) {
				$this->error('错误：验证码错误，请重新输入。');
			}
		}
		
		//禁止IP	
		if (C('filter_ip')) {
			$ban_ip = split_ip(trim(C('filter_ip')));
			if (is_array($ban_ip) && count($ban_ip)) {
				foreach ($ban_ip as $val) {
					$val = str_replace( '\*', '.*', preg_quote($val, "/") );
					if (preg_match("/^$val/", get_client_ip())) {
						$this->error('错误：您的IP已经被系统禁止发表留言/评论。');
					}
				}
			}
		}
		
		//留言时间间隔
		if (C('space')) {
			$lastposttime = Cookie::get('post_time');
			if (C('space') && time() - $lastposttime <= C('space')){
				$this->error('错误：您两次发表间隔应该大于'.C('space').'秒。');
			}
		}
		
		$gb  =  D ('Comment');
		$cookietime = 3600*24;
		
		if($gb->create()) {
		
			$gb->comment_author  = trim(strip_tags($gb->comment_author));
			$gb->comment_email   = trim($gb->comment_email);
			$gb->comment_url     = $gb->comment_url ? trim($gb->comment_url) : NULL;
			$gb->comment_ip      = get_client_ip();
			$gb->comment_content = preg_replace('/<(\/?)(script|i?frame|style|html|body|title|link|meta|img|\?|\%)([^>]*?)>/isU', '', $gb->comment_content);
			
			//过滤用户名
			$res = filter_name($gb->comment_author);
			switch($res) {
				case '0' : $this->error('错误：用户名太长。');
				case '-1' : $this->error('错误：此用户名包含不可接受字符，请选择其它用户名。');
				case '-2' : $this->error('错误：此用户名被管理员屏蔽，请选择其它用户名。');
			}
			
			//链接次数
			if (C('spam_url_num')) {
				if (substr_count($gb->comment_content, 'http://') >= C('spam_url_num')) {
					$spam = true;
				}
			}
		
			//过滤内容
			if (C('filter_words')) {
				$ban_words = explode('|',trim(C('filter_words')));	
				if (is_array($ban_words) && count($ban_words) ) {
					foreach ($ban_words as $val) {
						if ($val) {
							if (preg_match( "/".preg_quote($val, '/' )."/i", $gb->comment_content)) {
								$spam = true;
								break;
							}
						}
					}
				}
			}
			
			//表情处理
			
				
			//内容长度
			if (strlen($gb->comment_content) >= C('comment_maxlength')) {
				$this->error('错误：您的留言内容长度不符合要求，最多'.C('comment_maxlength').'个字节数。');
			} 
			else if (strlen($gb->comment_content) < C('comment_minlength')) {
				$this->error('错误：您的留言内容长度不符合要求，最少'.C('comment_minlength').'个字节数。');
			}
			
			$gb->comment_visible = $spam ? '0' : '1';
			
			$map  =	 array();
			$map['comment_author']  = $gb->comment_author;
			$map['comment_content'] = $gb->comment_content;
			$list = $gb->where($map)->find();
			if ($list['comment_id']) {
				$this->error('错误：重复发表留言，您好像发表过类似的留言。');
			}
			if ($vo = $gb->add()) {
				Cookie::set('comment_author_'. C('COOKIEHASH'), $gb->comment_author, $cookietime, C('COOKIEPATH'));
				Cookie::set('comment_email_'. C('COOKIEHASH'), $gb->comment_email, $cookietime, C('COOKIEPATH'));
				Cookie::set('comment_url_'. C('COOKIEHASH'), $gb->comment_url, $cookietime, C('COOKIEPATH'));
				Cookie::set('post_time',time());
				if ($spam) {
					$this->ajaxReturn('','此留言需要管理员审核后才能显示',0);
				}
				//发送邮件处理
				$output = $this->guestbookGetName($gb->comment_content);
				if ($output) {
					$emails = $this->guestbookGetEmail();
					foreach ($output as $name) {
						if (array_key_exists($name,$emails)) {
							$to = $emails["$name"];
							$this->sendEmailForGuestbook($vo, $name, $to, $gb->comment_author);
						}
					}
				}
				//处理热度
				$com_id = $this->guestbookGetId($gb->comment_content);
				$pk   =  $gb->getPk();
				$condition = array ($pk => array ('in', $com_id));
				$gb->where($condition)->setInc('comment_replaynum');
				
				$gb->comment_addtime = date('F jS, Y', $gb->comment_addtime).' at '.date('G:i', $gb->comment_addtime);
				
				//构造新留言html
				$html  = '<li class="comment" id="comment-'.$vo.'"><div id="comment-'.$vo.'-"><div class="userinfo">';
				$html .= '<div class="userpic"><img src="'.get_gravatar($gb->comment_email).'" class="avatar avatar-24 photo" width="24" height="24"></div>';
				$html .= '<div class="usertext"><div class="username">';
				if ($gb->comment_url) {
					$html .= '<a id="reviewer-'.$vo.'" href="'.$gb->comment_url.'" rel="external nofollow">'.$gb->comment_author.'</a>';
				} else {
					$html .= '<span id="reviewer-'.$vo.'">'.$gb->comment_author.'</span>';
				}
				$html .= ' <a class="anchor" rel="nofollow" href="#comment-'.$vo.'">#'.$vo.'</a></div>';
				$html .= '<div class="date">'.$gb->comment_addtime.'</div></div><div class="fixed"></div></div><div class="comment_text">';
				$html .= '<div id="commentbody-'.$vo.'"><p>'.convert_smilies($gb->comment_content).'</p></div></div></div></li>';
				
				$this->ajaxReturn($html,'',1);
				
            } else {
                $this->error('Oops, failed to post data.');
            }
		}else{
			$this->error($gb->getError());
		}
	}
	
	public function detailGuestbook() {
	
		if ($_REQUEST['act'] == 'detail_ajax') {
		
			$id = $_GET['id'];
			
			/* 查询过滤 */
			$map  =	 array();
			$map['comment_id'] = $id; 		
			$map['comment_visible'] = 1;
			$map['comment_type'] = 2; 	
			
			$gb = M('Comment');
			$vo	= $gb->where($map)->find();
			
			/* 用户头像 */
			$element_avatar = get_gravatar($vo['comment_email'], $s = 80, $d = C('avatar_default'), $r = C('avatar_rating'));
			
			/* 日期 */
			$datetime = date('F jS, Y', $vo['comment_addtime']).' at '.date('G:i', $vo['comment_addtime']);
			
			$result  = '<div class="userinfo">';
			$result .= '<div class="userpic"><img src="'.$element_avatar.'" class="avatar avatar-24 photo" width="24" height="24"></div>';
			$result .= '<div class="usertext"><div class="username">';
			if ($vo['comment_url']) {
				$result .= '<a id="reviewer-'.$vo['comment_id'].'" href="'.$vo['comment_url'].'" rel="external nofollow">'.$vo['comment_author'].'</a>';
			} else {
				$result .= '<span id="reviewer-'.$vo['comment_id'].'">'.$vo['comment_author'].'</span>';
			}
			$result .= ' <a class="anchor" rel="nofollow" href="#comment-'.$vo['comment_id'].'">#'.$vo['comment_id'].'</a></div><div class="date">'.$datetime.'</div></div>';
			$result .= '<div class="count"></div>';
			$result .= '<div class="fixed"></div></div>';
			$result .= '<div class="comment_text"><div id="commentbody-'.$vo['comment_id'].'">';
			$result .= '<p>'.$vo['comment_content'].'</p></div></div>';
			
			echo $result;
			
		} else {
			$this->error('非法操作');
		}
	}
	
	//获取用户留言内容中回复的人的昵称
	protected function guestbookGetName($content) {
	
		$content = preg_replace('/<a\shref="#comment-[0-9]+">/s','',$content);
		$content = preg_replace('/<a\shref="#comment-([0-9])+"\srel="nofollow">/s','',$content);
		$content = preg_replace('/<a\srel="nofollow"\shref="#comment-([0-9])+">/s','',$content);
		$names   = explode(' ',$content);

		$output = array();
		foreach($names as $val){
			$number = substr_count($val,'@');
			if ($number >0 ){
				$length = strlen($val);
				$pos = strrpos($val,'@')+1;
				$n = substr($val,$pos,$length);
				$output["$n"] = $n;
			}
		}
		return $output;
	}
	
	//获取用户邮件
	protected function guestbookGetEmail(){
		$gb  =  M ('Comment');
		$map['comment_visible'] = 1;
		$map['comment_type'] = 2; 
		$map['comment_notify'] = 1;
		$list = $gb->where($map)->order('comment_id desc')->findAll();
		$temp =array();
		foreach ($list as $val){
			$name = $val['comment_author'];
			if(!array_key_exists($name,$temp)){
				$email = $val['comment_email'];
				$temp["$name"] = $email;
			}
		}
		return $temp;
	}
	
	//发送邮件
	protected function sendEmailForGuestbook($id, $name, $to, $comment_author) {
	
		$body = $name.'，您好：<br/>您在 '.C('blog_name').' 上的留言被（'.$comment_author.'）回复了，快去看看吧^_^<br/>';
		$body .= '<div style="margin-top:10px;margin-left:10px;padding-bottom:10px;border-bottom:1px solid #ccc;">';
		$body .= '<a href=\''.C('blog_domain').'Guestbook#comment-'.$id.'\' target=\'_blank\'>查看回复</a></div>';
		$body .= '<p>感谢您对 <a href="'.C('blog_domain').'">'.C('blog_name').'</a> 的关注</p>';
		$body .= '<p><strong>This email was sent automatically. Please don\'t reply to this email.</strong></p>';
		
		import('@.ORG.Phpmailer');				
		$mail = new PHPMailer();   
		$mail->IsSMTP();
		$mail->Username = C('smtp_user'); 
		$mail->Password = C('smtp_pass');
		$mail->From     = C('smtp_mail');   
		$mail->Host     = C('smtp_host');
		$mail->Port     = C('smtp_port');
		$mail->Mailer   = "smtp";   
		$mail->FromName = C('blog_name'); 
		$mail->IsHTML(true); 
		$mail->SMTPAuth = true;
		$mail->CharSet  = "utf-8";
		$mail->Encoding = "base64";  
		$mail->Subject  = '您在 '.C('blog_name').' 上的留言刚刚被 '.$comment_author.' 回复了'; 
		$mail->AddAddress("$to", "");
		$mail->Body     = $body;
		@$mail->Send();
		// Clear all addresses and attachments for next loop   
		$mail->ClearAddresses();   
		$mail->ClearAttachments();
	}
	
	//他妈不会正则,怎么办
	protected function getId($content) {
		$reg = '/\shref="#comment-([0-9]+)/s';
		preg_match_all($reg , $content , $out_ary);
		return $out_ary[1];
	}

}

?>